package cn.hchaojie.javase.week2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Charts extends Application {
	public static void main(String[] args) {
		launch(args);
	}
	
	// TODO 从文件里面读取分数信息
	private static Map<String, List<Score>> readScores() {
		Map<String, List<Score>> scores = new HashMap<>();
		
		List<Score> scores1 = new ArrayList<>();
		scores1.addAll(Arrays.asList(
				new Score(88, "张三", "语文"),
				new Score(50.5, "李四", "语文"),
				new Score(77, "王五", "语文"),
				new Score(23, "赵六", "语文"),
				new Score(99, "刘琦", "语文"),
				new Score(100, "汪八", "语文")
		));
		
		List<Score> scores2 = new ArrayList<>();
		scores2.addAll(Arrays.asList(
				new Score(100, "张三", "数学"),
				new Score(55, "李四", "数学"),
				new Score(99, "王五", "数学"),
				new Score(88, "赵六", "数学"),
				new Score(72, "刘琦", "数学"),
				new Score(90, "汪八", "数学")
		));
		
		scores.put("语文", scores1);
		scores.put("数学", scores2);
		
		return scores;
	}

	@Override
	public void start(Stage primaryStage) throws Exception {
		VBox box = new VBox();
		
		Map<String, List<Score>> scores = readScores();
		for (Entry<String, List<Score>> entry : scores.entrySet()) {
			box.getChildren().add(createChart(entry.getValue()));
		}
		
		// 根据图表创建Scene场景
		Scene scene = new Scene(box);
		
		// 场景添加到舞台
		primaryStage.setScene(scene);
		primaryStage.show();
	}
	
	private static LineChart<String, Number> createChart(List<Score> scores) {
		// 创建x轴
		CategoryAxis xAxis = new CategoryAxis();
		NumberAxis yAxis = new NumberAxis();

		xAxis.setLabel("姓名");
		yAxis.setLabel("分数");

		LineChart<String, Number> lineChart = new LineChart<>(xAxis, yAxis);

		// 坐标点的数据
		XYChart.Series<String, Number> series = new XYChart.Series<>();
		
		for (Score s : scores) {
			series.getData().add(new Data<String, Number>(s.getName(), s.getScore()));
		}

		// 数据添加到图表
		lineChart.getData().add(series);
		return lineChart;
	}
}
